﻿// ==============================================================================
// Copyright (c) 2012 Bndy.Net, All rights reserved.
// Created by Bndy on 3/21/2012 9:37:21 PM
//
//                    * * * * * * * * * * * * * 
//                    * MAIL- bndy5337@163.com *       http://www.bndy.net
//                    * Q Q - 81795705 =========================================>
//                    * MSN - bndy5337@msn.com *
//                    * * * * * * * * * * * * * 
//
// ------------------------------------------------------------------------------
// 
// ==============================================================================

using System.Collections.Generic;

namespace Net.Bndy.Web
{
   public static class UrlHelper
    {
        public static string SetQueryString(string key, object value, string url = null)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();

            if (string.IsNullOrEmpty(url))
            {
                url = System.Web.HttpContext.Current.Request.Url.ToString();
            }

            Dictionary<string, string> lstQueryString = new Dictionary<string, string>();

            int idxSep = url.IndexOf('?');
            if (idxSep > 0)
            {
                foreach (string s in url.Substring(idxSep + 1, url.Length - idxSep - 1).Split('&'))
                {
                    string tmpKey = s.Split('=')[0];
                    string tmpValue = s.IndexOf('=') > 0 ? s.Split('=')[1] : string.Empty;

                    if (!lstQueryString.ContainsKey(tmpKey))
                    {
                        lstQueryString.Add(tmpKey, tmpValue);
                    }
                }
            }

            if (!string.IsNullOrEmpty(key))
            {
                if (value == null)
                    value = string.Empty;

                if (!lstQueryString.ContainsKey(key))
                    lstQueryString.Add(key, value.ToString());
                else
                    lstQueryString[key] = value.ToString();
            }

            result.AppendFormat("{0}?", idxSep > 0 ? url.Substring(0, idxSep) : url);

            foreach (KeyValuePair<string, string> kvp in lstQueryString)
            {
                result.AppendFormat("{0}={1}&", kvp.Key, kvp.Value);
            }

            result.Remove(result.Length - 1, 1);

            return result.ToString();
        }

        public static string GetQueryString(string key)
        {
            return System.Web.HttpContext.Current.Request.QueryString[key];
        }
    }
}